<template>
  <view class="experience">
    <view class="experience-content">
      <view class="title">
        <text class="text">工作经历</text>
      </view>
      <view class="form">
        <view class="edu-item" v-for="(work, index) in form.works" :key="index">
          <view class="form-top">
            <view class="form-item">
              <view class="form-item-content">
                <view class="label">
                  <text class="required">*</text>
                  <text class="text">
                    公司：
                  </text>
                </view>
                <view class="form--item-content-right">
                  <u-input 
                    v-model="work.company" 
                    placeholder="请输入公司名称"
                    input-align="right"
                    @blur="validateField('company', index)"
                  />
                  <text class="error" v-if="work.errors.company">{{ work.errors.company }}</text>
                </view>
              </view>
            </view>
            <view class="form-item">
              <view class="form-item-content">
                <view class="label">
                  <text class="required">*</text>
                  <text class="text">
                    职位：
                  </text>
                </view>
                <view class="form--item-content-right">
                  <u-input 
                    v-model="work.job" 
                    placeholder="请输入职位名称"
                    input-align="right"
                    @blur="validateField('job', index)"
                  />
                  <text class="error" v-if="work.errors.job">{{ work.errors.job }}</text>
                </view>
              </view>
            </view>
            <view class="form-item">
              <view class="form-item-content">
                <view class="label">
                  <text class="required">*</text>
                  <text class="text">在职时间：</text>
                </view>
                <view class="form--item-content-right">
                  <view class="input-date">
                    <u-input 
                      v-model="work.startdate" 
                      disabled 
                      placeholder="开始时间"
                      input-align="center"
                      @click="handleShowTime(index, 'startdate')"
                    />
                    <text class="separator">-</text>
                    <u-input 
                      v-model="work.stopdate" 
                      disabled 
                      placeholder="结束时间"
                      input-align="right"
                      @click="handleShowTime(index, 'stopdate')"
                    />
                  </view>
                  <text class="error" v-if="work.errors.date">{{ work.errors.date }}</text>
                </view>
              </view>
            </view>
          </view>

          <view class="form-item boder-none">
            <view class="form-item-content">
              <view>工作内容：</view>
            </view>
            <view class="input-desc">
              <u-input
                v-model="work.workdesc" 
                type="textarea"
                height="200"
                maxlength="500"
                :clearable="false"
                placeholder="描述工作职责和成果"
              />
            </view>
          </view>
          <view class="btn-delete" @click="removeItem(index)">删除工作经历</view>
        </view>
      </view>
    </view>
    <view class="btn-add" @click="handleAddWork">
      <text class="icon icon-add"></text>
      新增工作经历
    </view>

    <u-picker
      class="form-time"
      mode="time"
      v-model="showTime"
      :params="timeParams"
      :start-year="timeStart"
      :end-year="timeEnd"
      :default-time="defaultTime || ''"
      @confirm="handleConfirm"
    ></u-picker>
  </view>
</template>
<script>
import { formatTime } from '@/utils/handle';
export default {
  props: {
    work: {
      type: Array,
      default: () => ([]),
    },
  },
  data() {
    return {
      form: {
        works: [
          {
            company: "",
            job: "",
            startdate: "",
            stopdate: "",
            workdesc: "",
            errors: {
              company: "",
              job: "",
              date: ""
            }
          },
        ],
      },
      showTime: false,
      timeParams: {
        year: true,
        month: true,
        day: true,
        hour: false,
        minute: false,
        second: false,
      },
      timeStart: new Date().getFullYear() - 70,
      timeEnd: 2100,
      defaultTime: '',
      selectedIndex: '',
      timeType: '',
    };
  },
  watch: {
    work: {
      handler(newVal) {
        this.form.works = newVal.map(item => ({
          ...item,
          errors: { company: "", job: "", date: "" }
        }));
      },
      deep: true,
      immediate: true,
    },
    showTime(val) {
      if (!val) {
        this.validateDate(this.selectedIndex);
      }
    },
  },
  methods: {
    handleConfirm(e) {
      this.form.works[this.selectedIndex][this.timeType] = `${e.year}-${e.month}-${e.day}`;
    },
    handleAddWork() {
      // if (!this.validateAll()) return;
      for (let i = 0; i < this.form.works.length; i++) {
        const work = this.form.works[i];
        if (!work.company || !work.job || !work.startdate || !work.stopdate) {
          // 弹窗提示用户
          uni.showModal({
            title: '提示',
            content: '已有工作经历中存在未填写的必填项，请先完善',
            success: function (res) {
              if (res.confirm) {
              } else if (res.cancel) {
              }
            }
          });
          return; // 阻止新增工作经历
        }
      }

      this.form.works.push({
        company: "",
        job: "",
        startdate: "",
        stopdate: "",
        workdesc: "",
        errors: {
          company: "",
          job: "",
          date: ""
        }
      });
    },
    handleShowTime(index, item) {
      this.timeType = item;
      this.selectedIndex = index;
      this.showTime = true;
      let isIos = uni.getSystemInfoSync().platform == "ios";
      this.defaultTime = isIos? '' : (this.form.works[index][item] || formatTime(new Date(), "yyyy-MM-dd"));
    },
    removeItem(index) {
      this.form.works.splice(index, 1);
    },
    // 单个字段校验
    validateField(field, index) {
      const work = this.form.works[index];
      let isValid = true;

      switch(field) {
        case "company":
          work.errors.company = work.company ? "" : "公司名称不能为空";
          isValid = !work.errors.company;
          break;
          
        case "job":
          work.errors.job = work.job ? "" : "职位名称不能为空";
          isValid = !work.errors.job;
          break;
      }

      // 触发时间校验
      if (["company", "job"].includes(field)) {
        this.validateDate(index);
      }
      
      return isValid;
    },
    // 时间校验
    validateDate(index) {
      const item = this.form.works[index];
      if (!item.startdate || !item.stopdate) {
        item.errors.date = "请选择完整时间范围";
        return false;
      }
      
      if (new Date(item.startdate) >= new Date(item.stopdate)) {
        item.errors.date = "开始时间不能晚于结束时间";
        return false;
      }
      
      item.errors.date = "";
      return true;
    },
    // 全局校验
    validateAll() {
      let isValid = true;
      this.form.works.forEach((work, index) => {
        if (!this.validateField('company', index)) isValid = false;
        if (!this.validateField('job', index)) isValid = false;
        if (!this.validateDate(index)) isValid = false;
      });
      if (isValid) {
        this.$emit('submit', this.form.works)
      }
      return isValid;
    },
    exportData() {
      this.$emit('submit', this.form.works);
    },
  },

};
</script>
<style lang="scss" scoped>
.experience {
  .experience-content {
    border-radius: 30rpx;
    margin-top: 24rpx;
    padding: 24rpx 20rpx 1px 20rpx;
    background-color: #ffffff;
    box-shadow: 0rpx 4rpx 8rpx 0rpx rgba(0,0,0,0.05);
  }
  
  .title {
    font-weight: 500;
    font-size: 36rpx;
    color: #222222;
  }
}

.form {
  .btn-delete {
    padding: 12rpx 0;
    color: #F04646;
    font-size: 28rpx;
    text-align: center;
  }

  .edu-item {
    margin-bottom: 32rpx;
    padding: 12rpx 0;
  }
}

.btn-add {
  margin-top: 24rpx;
  padding: 36rpx 0;
  font-size: 28rpx;
  color: #222222;
  line-height: 28rpx;
  text-align: center;
  border-radius: 30rpx 30rpx 30rpx 30rpx;
  background-color: #ffffff;

  .icon-add {
    width: 25rpx;
    height: 25rpx;
    margin-right: 12rpx;
    background: url($img-base + 'resume/add-circle.png') no-repeat 100% /100%;
  }
}

.form-top {
  padding: 0 12rpx;
}

.form-item {
  position: relative;
  margin-bottom: 36rpx;
  border-bottom: 1rpx solid #E5E5E5;

  &.boder-none {
    border: none;
  }

  &-content {
    display: flex;

    .label {
      width: 180rpx;
      margin-top: 16rpx;
      display: inline-block;
      padding-right: 20rpx;
      font-size: 28rpx;
      color: #222222;
      flex-shrink: 0;
    }

    .text {
      position: relative;
    }
    
    .required{
      color: #e64340;
    }

    .form--item-content-right {
      position: relative;
      flex: 1;
    }
  }

  .error {
    position: absolute;
    color: #e64340;
    font-size: 24rpx;
    margin-top: 10rpx;
    display: block;
    bottom: -34rpx;
    right: 0;
  }

  .input-date {
    display: flex;
    align-items: center;
  }

  .input-desc {
    margin-top: 26rpx;
    padding: 12rpx 26rpx;
    border: 1rpx solid #E5E5E5;
    border-radius: 20rpx;
  }
}
::v-deep .input-desc .u-input__textarea {
  font-weight: 400;
  font-size: 26rpx;
  color: #555555;
  line-height: 40rpx;
}
.separator {
  margin: 0 20rpx;
}
</style>